# -*- coding: utf-8 -*-
# $Id: batchesmodel.py 27 2009-02-15 19:46:27Z gkuznets $

# Copyright 2008, 2009 Grigoriy Kuznetsov (gkuznets@yandex.ru)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from PyQt4.QtCore import QAbstractListModel, Qt, QVariant, QString, SIGNAL
from PyQt4.QtGui import QBrush, QFont
from core.batch import Batch
from batchicon import renderBatchIcon

class BatchesModel(QAbstractListModel):
    """Модель для набора всех пачек работ"""
    
    def __init__(self, parent=None):
        QAbstractListModel.__init__(self, parent)
        self.__font = QFont("Arial", 10, 2)
    
    def data(self, mindex, role):
        if not mindex.isValid():
            return QVariant()
        
        if role == Qt.DisplayRole:
            return QVariant(QString(Batch.all()[mindex.row()].name()))
        
        if role == Qt.DecorationRole:
            return QVariant(renderBatchIcon(Batch.all()[mindex.row()]))
        
        if role == Qt.BackgroundRole:
            if Batch.all()[mindex.row()].marked:
                return QVariant(QBrush(Qt.red))
            else:
                return QVariant(QBrush(Qt.white))
            
        if role == Qt.FontRole:
            return QVariant(self.__font)
        return QVariant()
    
    def flags(self, mindex):
        if mindex.isValid():
            if mindex.row() > self.rowCount():
                print "Very big index.row()!"
            else:
                if Batch.all()[mindex.row()].group is None:
                    return Qt.ItemIsEnabled | Qt.ItemIsSelectable
                else:
                    return Qt.NoItemFlags
        else:
            return Qt.NoItemFlags
    
    def rowCount(self, parent_index=None):
        return len(Batch.all())
    
    def onChanges(self):
        # Бежим по всем нашим индексам и смотрим, как они изменились
        # Если число пачек изменилось, то нужно добавить новый или удалить устаревший индекс
        #if len(self.__indices) < len(Batch.all()):
        #    have_batches = map(lambda i:i.batch(), self.__indices)
        #    for b in set(Batch.all()) - set(have_batches):
        #        print "Adding index for batch "+str(b.name())
        #        self.__indices.append(BatchesModelIndex(b))
        #elif len(self.__indices) > len(Batch.all()):
        #    print "Removing index FIXME!"
        #    assert(False)
        self.emit(SIGNAL("modelReset()"))